"""
Description: Dictionary Lookup Form, CGI version.
Uses mysql via ODBC

"""
dicts = dict(
Cambridge="en: Cambridge International Dictionary of English", 
Longman="en: Longman Dictionary of Contemporary English",
Webster="en: Webster Collegiate Dictionary",
collins="en: Collins Cobuild Dictionary, 4th edition",
soule="en: Soule's Dictionary of Synonyms",
oxford="en: Concise Oxford English Dictionary (En-En)",
enua="ua: English-Ukrainian",
uaen="ua: Ukrainian-English",
ruua="ua: Russian-Ukrainian",
EngRus="ru: Apresyan (English-Russian)",
americana="ru: Americana English-Russian Encyclopedia",

)

THE_DATABASE = "dict"

#START_CURRENT_DICT = "Longman"
START_CURRENT_DICT = "Webster"

import cgi, sys


sys.stderr = sys.stdout                # redirect errors to browser


form = cgi.FieldStorage( )            # parse form data


print "Content-type: text/html\n"      # plus blank line

## k_words = ('word', 'next', 'hits')
#word =""

if form.has_key('word'):
	word= form['word'].value
	#print form['word'], '=',form['word'].value,"<br>"
else:
	word= ""

if form.has_key('next'):
	next= form['next'].value
	#print form['next'], '=',form['next'].value, "<br>"
else:
	next= ""


if form.has_key('hits'):
	hits= form['hits'].value
	#print form['hits'], "=", form['hits'].value, "<br>"
else:
	hits= 0


if form.has_key('dict'):
	dict= form['dict'].value
else:
	dict= START_CURRENT_DICT


if hits:
    MAX_ROWS = int(hits)
else:
    MAX_ROWS = 16


HTML_HEAD = """
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 TRANSITIONAL//EN">
<html>
<head>

 <title>Web Dictionary</title>
 <meta http-equiv="content-type" content="text/html; charset=utf-8" />
 <style type="text/css">
     body {padding: 1px; background: #f1eee7}
      p, body, table {font-family: "Arial Unicode MS", verdana, arial; font-size: 9pt;}
      i {font-family: georgia, arial}
      table { border: 1px solid #cdc1ae; border-collapse: collapse; padding: 0px; margin: 1px;}
      TH, {border: 1px solid #cdc1ae;  }
      /* DL {border: 2px solid #dad3ce; margin: 1px 80px ;}*/
      DT {text-align: left; border: 1px solid white; border-bottom: 1px solid #d5cdbf; border-right: 1px solid #e5dfce; color: #817e70;margin: 2px 80px ; padding: 5px 10px;  background: #eff4e5; font-weight: bold}
      DD {text-align: left; margin: 0px 80px ; padding: 2px 110px; background: #f9f9fb; vertical-align: }
      dd p {margin: 0px; padding: 1px}
      TD {border: 1px solid #cdc1ae; padding: 2px;vertical-align: top;}
      TR { padding: 2px;background:#fbf8e9 ; }
      h1 {font-family: verdana; letter-spacing: .2em;font-size: 10pt; color: #b6b099; font-weight: bold;}
      pre {font-family: "Lucida Console", "Lucida Sans Unicode"}
      A:link{Color : #00008B; Font-Family : Arial, Helvetica, sans-serif;Text-Decoration : none; }
      A:visited{Color : #00008B;Font-Family : Arial, Helvetica, sans-serif;Text-Decoration : none;}
      A:hover{Color : #A0522D;Font-Family : Arial, Helvetica, sans-serif;Text-Decoration : none;}
      .info {color: #bbbbbb; padding: 3px}
      .even {background-color: #f5f0df}
      input {border:1px solid #a3a3a3;background: #fffbd5; margin: 5px}
      .button {border:1px solid #d6d1c0; background: #e8e7d8 }
      table.search {border: 0px; background: #e8e7d8 }
      table.search td {text-align: right; border: 0px}
      .dbg {color:#eaebec} /* #e7e7cc */
      .prev{display: inline; float: left; text-align:left; width: 100px; }
      .next{display: inline; float: right; text-align: right; width: 100px; }
      select {background-color: white; color: gray; border:1px solid #b6b099;}
      .star {color:#395666}
      .m2{margin-left: 10px}
      .m3{margin-left: 18px}      
      .m2 b i {color: #996300}
      .p1 {color: #333b14}
      .col1{color: #660066}
      .col2{color: #006600}
      .col3{color: #857d49}
      .ex {color: #000099; color: #ca6900; font-family: arial; padding-left:5px}
      .com{color: darkred}
      .stress {font-weight: bold; font-style:normal}
      .ref{font-weight: bold; color: #009999}
      .col_darkslategray{color: Gray;}

 </style>
</head>
<body bgcolor="#ffffff" text="#000000" link="#000099" vlink="#330066" alink="#ff0000">
<div align="center">
"""

print HTML_HEAD

print "<h1>%s</h1>" % dicts[dict][4:]
print """
<table class="search" border="0" width="450">
 <form method="get" action="" name="q" id="q">
  <tr>
   <td width='300'>Lookup:
   <input type="text" name="word">
    <br>
   </td>
   <td><input class="button" type="submit" value="Search">
   </td>
  </tr>
    <tr valign="middle">
   <td>
"""

##<%--= '    <input type="hidden" name="dict_" value="%s">' % cur_dict --%>



print '<select name = "dict">\n'

for k,v in dicts.iteritems():
	print '<option value="%s">%s</option>\n' % (k,v)

print '</select>'
print """
    </td>
   <td>
"""

# generate max results sequence 
F1,F2,F3,F4 = [2 ** x for x in range (3,7)]

print ''' Show first <select name="hits">     
      <option value="%s">%s</option>
      <option value="%s">%s</option>
      <option value="%s">%s</option>
      <option value="%s">%s</option>   
''' % (F1,F1,F2,F2, F3,F3,F4,F4)

print '''<script language="JavaScript">
document.forms[0].elements["dict"].value="%s"
</script>
    ''' % (dict)


print """
    </select>&nbsp;
    </td>
  </tr>
 </form>
</table>
"""

import pyodbc
import cgi


if word:
	print '''<script language="JavaScript">
document.forms[0].elements["word"].value="%s"
document.forms[0].elements["hits"].value="%s"
document.forms[0].elements["dict"].value="%s"
</script>
    ''' % (word, hits, dict)

if next:
    next = int(next)
    
if not word:
    pass

else:
    query = "select * from %s.%s where" % (THE_DATABASE, dict)
    got_one = False
    if word:
        query += " headword like '"+ word + "%'"
        
    if next:
        query += " LIMIT "+ str(next) +", "+ str(MAX_ROWS)
    print "<pre class='dbg'>DBG: query=%s</pre>" % query
    
    
    cn = pyodbc.connect('DRIVER={MySQL ODBC 3.51 Driver};SERVER=localhost;DATABASE=%s;UID=dict_user;PWD=dict_user' % THE_DATABASE)
    cursor = cn.cursor()
    #cursor.execute("SET collation_server='utf8_general_ci'")
    #cursor.execute("SET character_set_server='utf8'")
    #cursor.execute("SET character_set_results='utf8'")    
    cursor.execute("SET CHARACTER SET utf8")
    cursor.execute("SET NAMES utf8")
    cursor.execute(query)
    
    rows = cursor.fetchmany(MAX_ROWS)
    
    next_row_count    = 0
    previous_row_count = 0
    current_row_count = len(rows)

    if not next:
        next =0
    next_row_count = next + current_row_count
    
    previous_row_count = next - MAX_ROWS

    PREVIOUS_LINK =  (previous_row_count > -1) and \
    '<a href=?word=%s&next=%s&hits=%s&dict=%s title="Previous Entries"> &laquo; Previous </a></b>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' \
    %  (word, previous_row_count, MAX_ROWS, dict) or ""
    #
    NEXT_LINK = (current_row_count >= MAX_ROWS) and \
    '<a href=?word=%s&next=%s&hits=%s&dict=%s  title="Next Entries"> Next &raquo;</a></b>&nbsp;' \
    % (word, next_row_count, MAX_ROWS, dict ) or ""
    #
    print PREVIOUS_LINK + NEXT_LINK
            
    print "  <dl>"
    for row in rows:
        print "  \n<dt>" + str( row[0] )+ "</dt>"
        print "  \n<dd>" + str( row[1].replace('\n','\n</dd>\n<dd>') )+ "</dd>"
        #
    print "</dl>"

    print "</table>"
    
    print PREVIOUS_LINK + NEXT_LINK
#
print """
</div>
</body>
</html>

"""